// index.js
import {
  login
} from "../../api/index"
Page({
  data: {
    show: false,
    columns: ['分销商端口', '总部端口'],
    account: "",
    pwd: "",
    role: "",

  },
  //输入账号
  account(event) {
    this.setData({
      account: event.detail.value
    });
  },
  pwd(event) {
    this.setData({
      pwd: event.detail.value
    });
  },
  showPopup() {
    this.setData({
      show: true
    });
  },

  onClose() {
    this.setData({
      show: false
    });
  },
  onChange(event) {
    const {
      picker,
      value,
      index
    } = event.detail;
    this.setData({
      role: value
    });
  },
  async toLogin() {
    if (!this.data.account) {
      wx.showToast({
        title: '请输入账号',
        icon: 'error'
      })
    } else if (!this.data.pwd) {
      wx.showToast({
        title: '请输入密码',
        icon: 'error'
      })
    } else if (!this.data.role) {
      wx.showToast({
        title: '请选择角色',
        icon: 'error'
      })
    } else {
      var role = this.data.role == '分销商端口' ? 3 : 2
      let res = await login({
        account: this.data.account,
        pwd: this.data.pwd,
        role_id: this.data.role == '分销商端口' ? 3 : 2
      })
      if (res) {
        if (res.msg == "操作成功" && role == 2) {
          wx.setStorageSync('isLogin', 2)
          wx.setStorageSync('info', res.dataset)
          wx.navigateTo({
            url: '/pages/main/index/index',
            success: () => {
              console.log("success")
            },
            fail: () => {
              console.log("fail")
            }
          })
        } else if (res.msg == "操作成功" && role == 3) {
          // console.log("分销商")
          wx.setStorageSync('isLogin', 3)
          wx.setStorageSync('info', res.dataset)
          wx.reLaunch({
            url: '/pages/distributor/index/index',
            success: () => {
              console.log("success")
            },
            fail: () => {
              console.log("fail")
            }
          })
        }
      }else {
        wx.showToast({
          title: '登陆失败',
          icon: "error"
        })
      }
    }

  },
  onLoad() {
    
    if (wx.getStorageInfoSync("isLogin")) {
      if (Number( wx.getStorageSync('isLogin')) == 2) {
        // console.log("success2")
        wx.navigateTo({
          url: '/pages/main/index/index',
          success: () => {
            // console.log("success2")
          },
          fail: () => {
            // console.log("fail")
          }
        })
      } else if (Number( wx.getStorageSync('isLogin')) == 3) {
        wx.reLaunch({
          url: '/pages/distributor/index/index',
          success: () => {
            // console.log("success3")
          },
          fail: () => {
            // console.log("fail")
          }
        })
      }
    }
  },
  onShow() {
    wx.hideHomeButton()
  }


})